package com.stylefeng.guns.modular.clm.controller;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.jms.Destination;

import org.apache.activemq.command.ActiveMQTopic;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.jms.Producer;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.core.util.Queue.MyBlockingQueue.Basket;
import com.stylefeng.guns.core.util.clm.AdminConstant;
import com.stylefeng.guns.core.util.clm.AdminTools;
import com.stylefeng.guns.core.util.clm.RedisService;
import com.stylefeng.guns.modular.clm.service.IClmRoomService;
import com.stylefeng.guns.modular.system.model.ClmAreaEntity;
import com.stylefeng.guns.modular.system.model.ClmRoom;
import com.stylefeng.guns.modular.system.model.ClmSubjectEntity;

/**
 * 监控课堂并发数
 * @author yc
 *
 */
@Controller
@RequestMapping("/mon")
public class ClmMonitoringController extends BaseController{
	private final static Logger log = LoggerFactory.getLogger(ClmMonitoringController.class);
	
	@Autowired
	private RedisService redisService ;
	
	@Autowired  
    private Producer producer; 
	
    @Autowired
    private IClmRoomService clmRoomService;
    
    static Basket basket = new Basket();
    
    private String PREFIX = "/clm/clmMonitor/";
    /** 模块路径*/
	private final String MODULE_PATH="clm/monitoring/";
	public static Map<String,String> room_num_map=new ConcurrentHashMap<String,String>();
	
	/*static{
		updateMap();
	}*/
	
	@RequestMapping("roomPeopleCallback")
	public void roomPeopleNum(){
		try {
			String classNo=this.getPara("ClassNo");
			String operator=this.getPara("Operator");
			String action=this.getPara("Action");//101—用户进入  107—退出直播教室 110—用户异常离开 105—停止直播
			String totalusernum=this.getPara("totalusernum");
			log.info("课堂id="+classNo+" 课堂人数："+totalusernum+" operator="+operator+" action="+action);
			if(StringUtils.isBlank(classNo)){
				return;
			}
			StringBuffer sb=new StringBuffer();
			String roomPeopleStr=sb.append(action).append(",")
					.append(classNo).append(",")
					.append(totalusernum).append(",")
					.append(operator).toString();
			//发送消息队列
			//队列模式
	        /*Destination destination = new ActiveMQQueue("mytest.queue");  
	        producer.sendQueueMessage(destination, "myname is queue!!!");*/  
	        //主题模式
			Destination destination = new ActiveMQTopic("roomPeople.topic");
			producer.sendTopicMessage(destination, roomPeopleStr); 

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
		
	}
	

	 
	 public static void updateMap(){
		 class Consumer implements Runnable {
			   public void run() {
			    try {
			      // 消费苹果
			      String roomPeopleStr=basket.consume();
			      String[] s_tmp={};
			      if(StringUtils.isNotBlank(roomPeopleStr)){
						log.info("roomPeopleStr="+roomPeopleStr);
						s_tmp=roomPeopleStr.split(",");
						if("105".equals(s_tmp[0])){
							//课程结束
							room_num_map.remove(s_tmp[1]);
						}else{
							room_num_map.put(s_tmp[1], s_tmp[2]);
						}
			      	}
			      
			    } catch (InterruptedException ex) {
			    }
			   }
			  }
		 
		 //创建一个可缓存的线程池
		 ExecutorService service = Executors.newCachedThreadPool();
		 while(true){
			 if(basket.getAppleNumber()>0){
				 Consumer consumer = new Consumer();
				  service.submit(consumer); 
			 }else{
				 try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			 }
			 
		 }
		 
	 }
	

	
    /**
     * 跳转到监控列表
     */
    @RequestMapping("/monitor")
    public String index(Model model) {
    	try {
    		
    		/*List<com.dubbox.plat.entity.ClmAreaEntity> provinceList1 = PlatFactory.getClmAreaRemote().findProvinceList("002");
    		System.out.println(provinceList1.toString());*/
    		//获取省列表
    		List<ClmAreaEntity> l_province = null;
    		if(redisService.exists("clmAdminProvinceList"+AdminConstant.DEFAULT_SITEID)){
    			l_province = (List<ClmAreaEntity>) redisService.get("clmAdminProvinceList"+AdminConstant.DEFAULT_SITEID);
    			if(l_province !=null && l_province.size()>0){
    				model.addAttribute("provinceList",l_province);
    			}else{
    				String provinceList=AdminTools.findProvinceList("",AdminConstant.DEFAULT_SITEID);
    				if(StringUtils.isNotBlank(provinceList)){
    					JSONObject jsonObj=JSON.parseObject(provinceList);
    					l_province=JSON.parseArray(jsonObj.get("message").toString(), ClmAreaEntity.class);
    					model.addAttribute("provinceList",l_province);
    					redisService.set("clmAdminProvinceList"+AdminConstant.DEFAULT_SITEID, l_province);
    				}
    			}
    			
    		}else{
				String provinceList=AdminTools.findProvinceList("",AdminConstant.DEFAULT_SITEID);
				if(StringUtils.isNotBlank(provinceList)){
					JSONObject jsonObj=JSON.parseObject(provinceList);
					l_province=JSON.parseArray(jsonObj.get("message").toString(), ClmAreaEntity.class);
					model.addAttribute("provinceList",l_province);
					redisService.set("clmAdminProvinceList"+AdminConstant.DEFAULT_SITEID, l_province);
				}
			}
    		
			
			//获取科目列表
    		List<ClmSubjectEntity> l_subject = null;
    		if(redisService.exists("clmAdminSubjectList"+AdminConstant.DEFAULT_SITEID)){
    			l_subject = (List<ClmSubjectEntity>) redisService.get("clmAdminSubjectList"+AdminConstant.DEFAULT_SITEID);
    			if(l_subject !=null && l_subject.size()>0){
    				model.addAttribute("subjectList",l_subject);
    			}else{
    				String subjectList=AdminTools.findAllSubject(AdminConstant.DEFAULT_SITEID);
	    			if(StringUtils.isNotBlank(subjectList)){
	    				JSONObject jsonObj=JSON.parseObject(subjectList);
	    				l_subject=JSON.parseArray(jsonObj.get("allSubject").toString(), ClmSubjectEntity.class);
	    				model.addAttribute("subjectList",l_subject);
	    				redisService.set("clmAdminSubjectList"+AdminConstant.DEFAULT_SITEID, l_subject);
	    			}
    			}
    			
    		}else{
    			String subjectList=AdminTools.findAllSubject(AdminConstant.DEFAULT_SITEID);
    			if(StringUtils.isNotBlank(subjectList)){
    				JSONObject jsonObj=JSON.parseObject(subjectList);
    				l_subject=JSON.parseArray(jsonObj.get("allSubject").toString(), ClmSubjectEntity.class);
    				model.addAttribute("subjectList",l_subject);
    				redisService.set("clmAdminSubjectList"+AdminConstant.DEFAULT_SITEID, l_subject);
    			}
    		}
    		
			
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
        return PREFIX + "clmMonitor.html";
    }
	
	
	
    /**
     * 获取列表
     */
    @RequestMapping(value = "/roomList")
    @ResponseBody
    public Object roomList(ClmRoom clmRoom) {
    	EntityWrapper<ClmRoom> entityWrapper=new EntityWrapper<ClmRoom>();
    	Wrapper<ClmRoom> wrapper=null ;
    	log.info("==================="+clmRoom.toString());
    	if(StringUtils.isNotBlank(clmRoom.getTeacherName())){
    		entityWrapper.eq("teacher_name", clmRoom.getTeacherName());
    	}
    	if(StringUtils.isNotBlank(clmRoom.getOrgProvinceCode())){
    		entityWrapper.eq("org_province_code", clmRoom.getOrgProvinceCode());
    	}
    	if(StringUtils.isNotBlank(clmRoom.getOrgCityCode())){
    		entityWrapper.eq("org_city_code", clmRoom.getOrgCityCode());
    	}
    	if(StringUtils.isNotBlank(clmRoom.getOrgAreaCode())){
    		entityWrapper.eq("org_area_code", clmRoom.getOrgAreaCode());
    	}
    	if(StringUtils.isNotBlank(clmRoom.getSchoolId())){
    		entityWrapper.eq("school_id", clmRoom.getSchoolId());
    	}
    	/*if(StringUtils.isNotBlank(clmRoom.getRoomId())){
    		entityWrapper.eq("room_id", clmRoom.getRoomId());
    	}*/
    	if(StringUtils.isNotBlank(clmRoom.getNumber())){
    		entityWrapper.eq("number_", clmRoom.getNumber());
    	}
    	if(StringUtils.isNotBlank(clmRoom.getSubject())){
    		entityWrapper.like("subject_", clmRoom.getSubject());
    	}
    	if(StringUtils.isNotBlank(clmRoom.getLiveType())){
    		entityWrapper.eq("live_type", clmRoom.getLiveType());
    	}
    	if(StringUtils.isNotBlank(clmRoom.getPublicScope())){
    		entityWrapper.eq("public_scope", clmRoom.getPublicScope());
    	}
    	if(StringUtils.isNotBlank(clmRoom.getCourseCode())){
    		entityWrapper.eq("course_code", clmRoom.getCourseCode());
    	}
    	if(ToolUtil.isNotEmpty(this.getPara("startDate1"))){
    		entityWrapper.ge("start_date", this.getPara("startDate1"));
    	}
    	if(ToolUtil.isNotEmpty(this.getPara("endDate1"))){
    		entityWrapper.le("invalid_date", this.getPara("endDate1"));
    	}
    	if(StringUtils.isNotBlank(this.getPara("roomStatus"))){
    		Date day=new Date();    
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    		if("1".equals(this.getPara("roomStatus"))){
    			//正在直播即将开始
    			entityWrapper.ge("invalid_date", df.format(day));
    		}else if("2".equals(this.getPara("roomStatus"))){
    			//已经结束
    			entityWrapper.le("invalid_date", df.format(day));
    		}
    	}   
    	
    	entityWrapper.eq("site_id", AdminConstant.DEFAULT_SITEID);
    	entityWrapper.eq("be_deleted", 0);
    	wrapper=entityWrapper.orderBy("start_date", false);
    	List<ClmRoom> l_clmRoom = clmRoomService.selectList(wrapper);
    	
    	/*room_num_map.put("O5jsbghQjb", ""+(int)(Math.random()*100));
    	room_num_map.put("yLndmd0RLH", ""+(int)(Math.random()*100));
    	room_num_map.put("F724PfD7hN", ""+(int)(Math.random()*100));*/
    	for(ClmRoom cr:l_clmRoom){
    		if(room_num_map.containsKey(cr.getRoomId())){
    			cr.setLookNum(room_num_map.get(cr.getRoomId()));
    		}else{
    			cr.setLookNum("0");
    		}
    	}
    	return l_clmRoom;
    }
	
    /**
     * 获取不同直播类型占用并发数
     */
    @RequestMapping(value = "/getLiveTypeNum")
    @ResponseBody
    public Object getLiveTypeNumBySiteId() {
    	Map<String, Object> liveTypenum=clmRoomService.getLiveTypeNumBySiteId(AdminConstant.DEFAULT_SITEID);
    	
    	return liveTypenum;
    }
    
    /**
     * 获取不同直播类型占用并发数
     */
    @RequestMapping(value = "/getLookNum")
    @ResponseBody
    public Object getLookNum() {
    	Map<String, String> map = new HashMap<String, String>(); 
    	int all_num=0;
    	//遍历map中的值 
    	for (String value : room_num_map.values()) { 
    		all_num +=Integer.parseInt(value);
    	  System.out.println("Value = " + value); 
    	}
    	
    	int my_num=0;
    	ClmRoom clmRoom=new ClmRoom();
    	List<ClmRoom> l_clmRoom =(List<ClmRoom>) roomList(clmRoom);
    	for(ClmRoom cl : l_clmRoom){
    		my_num += Integer.parseInt(cl.getLookNum());
    	}
    	
    	Date dt= new Date();
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    	map.put("date", df.format(dt));
    	map.put("all_num", all_num+"");
    	map.put("my_num", my_num+"");
    	
    	return map;
    }
    
    
    

}
